package udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/4/13
 * Time:21:00
 **/

//先运行服务器端，再客户端
public class UDPServer {
    /**
     * 服务器
     */
    //端口号
    private static final int port = 9001;
    //数据的最大值
    private static final int bleng = 1024;

    public static void main(String[] args) throws IOException {
        // 1.启动一个 UDP 服务器端(IP、端口号)
        DatagramSocket server = new DatagramSocket(port);
        System.out.println("服务器启动成功！");
        while(true){
            //2.初始化数据包
            DatagramPacket clientPacket = new DatagramPacket(
                    new byte[bleng],
                    bleng
            );
            //3.等待客户端的链接
            server.receive(clientPacket);
            // 执行到此步骤，表示已经有客户端连接

            //4.接收到客户端的信息
            String msg = new String(clientPacket.getData());//转换成String
            System.out.println("客户端："+msg);
            //给客户端一个响应
            String serMsg = "收到！";
            //发送消息
            DatagramPacket serverPacket = new DatagramPacket(//发送时四个参数
                    serMsg.getBytes(),//只认字节
                    serMsg.getBytes().length,// 注意是字节长度
                    clientPacket.getAddress(),
                    clientPacket.getPort()
            );
            //发送
            server.send(serverPacket);
        }
    }
}
